package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.Administrator;
import com.scuec.trainingmanagementsys.service.AdministratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/administrators")
@CrossOrigin
public class AdministratorController {

    private static final Logger logger = LoggerFactory.getLogger(AdministratorController.class);

    @Resource
    private AdministratorService administratorService;

    // 1. 整表查询（GET /api/administrators）
    @GetMapping
    public Result listAll() {
        try {
            List<Administrator> administrators = administratorService.listAll();
            return Result.success(administrators);
        } catch (Exception e) {
            logger.error("整表查询失败", e);
            return Result.fail("整表查询失败");
        }
    }

    // 2. 姓名模糊查询（GET /api/administrators?name=xxx）
    @GetMapping("/search")
    public Result listByName(@RequestParam(required = false) String name) {
        try {
            List<Administrator> administrators = administratorService.listByName(name);
            return Result.success(administrators);
        } catch (Exception e) {
            logger.error("姓名模糊查询失败", e);
            return Result.fail("姓名模糊查询失败");
        }
    }

    // 3. 删除单条记录（DELETE /api/administrators/{id}）
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        try {
            boolean result = administratorService.deleteById(id);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除单条记录失败", e);
            return Result.fail("删除单条记录失败");
        }
    }

    // 4. 批量删除（DELETE /api/administrators/batch）
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        try {
            boolean result = administratorService.deleteBatch(ids);
            if (result) {
                return Result.success("批量删除成功");
            } else {
                return Result.fail("批量删除失败");
            }
        } catch (Exception e) {
            logger.error("批量删除失败", e);
            return Result.fail("批量删除失败");
        }
    }

    // 5. 插入记录（POST /api/administrators）
    @PostMapping("/insertAdmin")
    public Result save(@RequestBody Administrator admin) {
        try {
            boolean result = administratorService.save(admin);
            if (result) {
                return Result.success("插入记录成功");
            } else {
                return Result.fail("插入记录失败");
            }
        } catch (Exception e) {
            logger.error("插入记录失败", e);
            return Result.fail("插入记录失败");
        }
    }

    // 6. 修改记录（PUT /api/administrators）
    @PutMapping("/update")
    public Result update(@RequestBody Administrator admin) {
        try {
            boolean result = administratorService.update(admin);
            if (result) {
                return Result.success("修改记录成功");
            } else {
                return Result.fail("修改记录失败");
            }
        } catch (Exception e) {
            logger.error("修改记录失败", e);
            return Result.fail("修改记录失败");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm) {
        try {
            String username = loginForm.getUsername();
            String password = loginForm.getPassword();
            String type = loginForm.getAdministratorType();

            // 调用Service层方法
            Administrator admin = administratorService.login(username, password, type);

            if (admin != null) {
                return Result.success(admin);
            } else {
                return Result.fail("登录失败");
            }
        } catch (Exception e) {
            logger.error("登录异常", e);
            return Result.fail("登录异常，请重试");
        }
    }

    // 根据管理员账号查询管理员
    @GetMapping("/profile/{administratorName}")
    public Result getAdministratorProfile(@PathVariable String administratorName) {
        try {
            Administrator admin = administratorService.getAdministratorByUsername(administratorName);
            if (admin != null) {
                return Result.success(admin);
            } else {
                return Result.fail("未找到该管理员信息");
            }
        } catch (Exception e) {
            logger.error("获取管理员信息失败", e);
            return Result.fail("获取管理员信息失败");
        }
    }

    // 根据管理员账号更新信息
    @PutMapping("/update/{administratorName}")
    public Result updateByAdministratorName(@PathVariable String administratorName, @RequestBody Administrator admin) {
        try {
            admin.setAdministratorName(administratorName);
            boolean result = administratorService.updateByAdministratorName(admin);
            if (result) {
                return Result.success("个人信息更新成功");
            } else {
                return Result.fail("个人信息更新失败");
            }
        } catch (Exception e) {
            logger.error("更新管理员信息失败", e);
            return Result.fail("更新管理员信息失败");
        }
    }

    // 新增：登录表单参数类（可放在单独文件LoginForm.java中）
    public static class LoginForm {
        private String username;
        private String password;
        private String administratorType;
        // Getter和Setter
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getAdministratorType() {
            return administratorType;
        }

        public void setAdministratorType(String administratorType) {
            this.administratorType = administratorType;
        }
    }

    // 新增：统一返回结果类（可放在common包下的Result.java中）
    public static class Result {
        private boolean success;
        private Object data;
        private String message;

        // 成功响应
        public static Result success(Object data) {
            Result r = new Result();
            r.success = true;
            r.data = data;
            return r;
        }

        public static Result success(String message) {
            Result r = new Result();
            r.success = true;
            r.message = message;
            return r;
        }

        // 失败响应
        public static Result fail(String message) {
            Result r = new Result();
            r.success = false;
            r.message = message;
            return r;
        }

        // Getter和Setter
        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

    @GetMapping("/count")
    public Result getAdministratorCount() {
        try {
            int count = administratorService.getAdministratorCount();
            return Result.success(count);
        } catch (Exception e) {
            logger.error("获取管理员总数失败", e);
            return Result.fail("获取管理员总数失败");
        }
    }
}